package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	arg_num := len(os.Args)
	if arg_num < 2 {
		fmt.Printf("the num of input is %d\n", arg_num)
		return
	}

	var port string = ":" + os.Args[1]

	conn, err := net.Dial("tcp", port)
	if err != nil {
		fmt.Printf("build linke error[%s]\n", err)
		return
	}

	var msg string = "{\"txn\":\"pull_req\",\"client\":\"cn-1562578\",\"time\":\"20170504155301\"}"
	mlen := len(msg)
	msg += "\r\n{\"type\":[\"type1\", \"type2\"]}"

	/*
		b := []byte{mlen >> 24, (mlen >> 16) & 0xff, (mlen >> 8) & 0xff, mlen & 0xff}
		b_buf := bytes.NewBuffer(b)

	*/

	b_buf := bytes.NewBuffer([]byte{})

	binary.Write(b_buf, binary.BigEndian, (int32)(mlen))
	b_buf.WriteString(msg)

	fmt.Fprintf(conn, b_buf.String())

	buf := make([]byte, 1024)
	length, err := conn.Read(buf)
	if err != nil {
		if strings.EqualFold(err.Error(), "EOF") == true {
			fmt.Println("client close link")
			return
		}
		fmt.Println("read error: %s", err.Error())
		return
	}

	b_buf = bytes.NewBuffer(buf)
	var len int32
	binary.Read(b_buf, binary.BigEndian, &len)

	head := string(buf[4 : len+4])
	body := string(buf[len+6:])

	fmt.Println("body:", body, "head:", head, "length:", length, "len:", len)

	return
}
